package com.stooscloud;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class BeanToMapUtil {

    public static Map<String, Object> beanToMap(Object obj) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Map<String, Object> params = new HashMap<String, Object>(0);
        PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
        PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
        for (int i = 0; i < descriptors.length; i++) {
            String name = descriptors[i].getName();
            if (!StringUtils.equals(name, "class")) {
                params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
            }
        }
        return params;
    }
}
